package com.gis3c.sys.security.shiro.token;

import com.gis3c.sys.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class StatelessRealm extends AuthorizingRealm {
	@Autowired private UserService userService;
	
	@Override
	public boolean supports(AuthenticationToken token){
		//仅支持StatelessToken类型的Token
		return token instanceof StatelessToken;
	}
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//		String username = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		StatelessToken statelessToken = (StatelessToken) token;

		String username = getUserName(statelessToken.getClientDigest());
		String key = getKey(username);

		//在服务器端生成客户端参数消息摘要
		String serverDigest = null;
		serverDigest = userService.createDigest(key, username);

		return new SimpleAuthenticationInfo(username,serverDigest,getName());
	}

	private String getUserName(String clientDigest){
		String userName = userService.getUserNameByToken(clientDigest);
		return userName == null ? "" : userName;
	}

	private String getKey(String username){
		return userService.findsecretByUserName(username);
	}
}
